<template>
  <div class="page-container">
    <div class="dashboard-container">
      <!-- 输入框和按钮 -->
      <div class="input-container">
    <input
      v-model="inputString"
      placeholder="请输入字符串"
      @keyup.enter="sendRequest"
        />
        <button @click="sendRequest">发送请求</button>
      </div>

      <!-- 统计卡片 -->
      <div class="stat-cards" v-if="response">
        <div class="stat-card">
          <div class="stat-title">总支出</div>
          <div class="stat-value expense">¥{{ totalExpense.toFixed(2) }}</div>
          <div class="stat-trend">
            环比: {{ monthOverMonthExpense > 0 ? '+' : '' }}{{ monthOverMonthExpense.toFixed(2) }}%
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-title">总收入</div>
          <div class="stat-value income">¥{{ totalIncome.toFixed(2) }}</div>
          <div class="stat-trend">
            月均: ¥{{ (totalIncome / monthCount).toFixed(2) }}
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-title">交易笔数</div>
          <div class="stat-value">{{ transactionCount }}笔</div>
          <div class="stat-trend">
            日均: {{ (transactionCount / dayCount).toFixed(1) }}笔
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-title">月均支出</div>
          <div class="stat-value">¥{{ monthlyAvgExpense.toFixed(2) }}</div>
          <div class="stat-trend">
            日均: ¥{{ averageDailyExpense.toFixed(2) }}
          </div>
        </div>
      </div>

      <!-- 图表网格 -->
      <div class="chart-grid">
        <!-- 月度收支趋势图 -->
        <div class="chart-container">
          <div id="monthlyTrendChart" class="chart"></div>
        </div>

        <!-- 消费类型饼图 -->
        <div class="chart-container">
          <div id="typeChart" class="chart"></div>
        </div>

        <!-- 每周消费趋势图 -->
        <div class="chart-container">
          <div id="weeklyTrendChart" class="chart"></div>
        </div>

        <!-- 支付方式分布 -->
        <div class="chart-container">
          <div id="paymentMethodChart" class="chart"></div>
        </div>

        <!-- 消费时段分布 -->
        <div class="chart-container">
          <div id="timeDistChart" class="chart"></div>
        </div>

        <!-- 商户TOP10 -->
        <div class="chart-container">
          <div id="merchantChart" class="chart"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from "vue";
import * as echarts from 'echarts';

const inputString = ref("");
const response = ref(null);
const totalExpense = ref(0);
const totalIncome = ref(0);
const transactionCount = ref(0);
const averageDailyExpense = ref(0);
const monthOverMonthExpense = ref(0);
const monthlyAvgExpense = ref(0);
const monthCount = ref(0);
const dayCount = ref(0);

let charts = {
  monthlyTrendChart: null,
  typeChart: null,
  weeklyTrendChart: null,
  paymentMethodChart: null,
  timeDistChart: null,
  merchantChart: null
};

// 初始化所有图表
const initCharts = () => {
  Object.keys(charts).forEach(key => {
    const dom = document.getElementById(key);
    if (dom) {
      charts[key] = echarts.init(dom);
    }
  });
};

// 更新所有图表
const updateCharts = (data) => {
  if (!data?.received_data?.bill_details || !Array.isArray(data.received_data.bill_details)) {
    console.error('Invalid data format');
    return;
  }

  const billDetails = data.received_data.bill_details;
  
  // 计算统计数据
  calculateStatistics(billDetails);
  
  // 更新各个图表
  updateMonthlyTrendChart(billDetails);
  updateTypeChart(billDetails);
  updateWeeklyTrendChart(billDetails);
  updatePaymentMethodChart(billDetails);
  updateTimeDistChart(billDetails);
  updateMerchantChart(billDetails);
};

// 计算统计数据
const calculateStatistics = (billDetails) => {
  let expense = 0;
  let income = 0;
  let monthlyExpenses = {};
  
  billDetails.forEach(item => {
    const amount = Number(item['金额(元)']);
    const date = new Date(item.交易时间);
    const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
    
    if (item.收支 === '支出') {
      expense += amount;
      if (!monthlyExpenses[monthKey]) {
        monthlyExpenses[monthKey] = 0;
      }
      monthlyExpenses[monthKey] += amount;
    } else {
      income += amount;
    }
  });

  // 计算月度环比变化
  const months = Object.keys(monthlyExpenses).sort();
  let monthOverMonth = 0;
  if (months.length >= 2) {
    const lastMonth = monthlyExpenses[months[months.length - 1]];
    const prevMonth = monthlyExpenses[months[months.length - 2]];
    monthOverMonth = ((lastMonth - prevMonth) / prevMonth) * 100;
  }

  // 计算日期范围
  const dates = billDetails.map(item => new Date(item.交易时间));
  const minDate = new Date(Math.min(...dates));
  const maxDate = new Date(Math.max(...dates));
  const dayCount = Math.ceil((maxDate - minDate) / (1000 * 60 * 60 * 24)) || 1;
  const monthCount = Object.keys(monthlyExpenses).length || 1;

  totalExpense.value = expense;
  totalIncome.value = income;
  transactionCount.value = billDetails.length;
  monthOverMonthExpense.value = monthOverMonth;
  monthlyAvgExpense.value = expense / monthCount;
  averageDailyExpense.value = expense / dayCount;
};

// 更新月度收支趋势图
const updateMonthlyTrendChart = (billDetails) => {
  // 按月份分组统计收支
  const monthlyStats = {};
  billDetails.forEach(item => {
    const date = new Date(item.交易时间);
    const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
    
    if (!monthlyStats[monthKey]) {
      monthlyStats[monthKey] = { income: 0, expense: 0 };
    }
    
    const amount = Number(item['金额(元)']);
    if (item.收支 === '支出') {
      monthlyStats[monthKey].expense += amount;
    } else {
      monthlyStats[monthKey].income += amount;
    }
  });

  const months = Object.keys(monthlyStats).sort();
  const option = {
    title: {
      text: '月度收支趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' }
    },
    legend: {
      data: ['收入', '支出'],
      top: 30
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: months,
      axisLabel: {
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: '金额 (元)'
    },
    series: [
      {
        name: '收入',
        type: 'bar',
        data: months.map(m => monthlyStats[m].income.toFixed(2)),
        itemStyle: { color: '#67C23A' }
      },
      {
        name: '支出',
        type: 'bar',
        data: months.map(m => monthlyStats[m].expense.toFixed(2)),
        itemStyle: { color: '#F56C6C' }
      }
    ]
  };

  charts.monthlyTrendChart?.setOption(option);
};

// 更新每周消费趋势
const updateWeeklyTrendChart = (billDetails) => {
  // 按周分组数据
  const weeklyData = {};
  billDetails.forEach(item => {
    if (item.收支 === '支出') {
      const date = new Date(item.交易时间);
      const year = date.getFullYear();
      const weekNum = getWeekNumber(date);
      const weekKey = `${year}年第${weekNum}周`;
      
      if (!weeklyData[weekKey]) {
        weeklyData[weekKey] = 0;
      }
      weeklyData[weekKey] += Number(item['金额(元)']);
    }
  });

  const weeks = Object.keys(weeklyData).sort();
  const option = {
    title: {
      text: '每周消费趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: '{b}<br/>消费金额: ¥{c}'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: weeks,
      axisLabel: {
        interval: 0,
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '金额 (元)'
    },
    series: [{
      name: '周消费',
      type: 'line',
      smooth: true,
      data: weeks.map(week => Number(weeklyData[week].toFixed(2))),
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(58,77,233,0.3)' },
          { offset: 1, color: 'rgba(58,77,233,0.1)' }
        ])
      },
      itemStyle: {
        color: '#3a4de9'
      }
    }]
  };

  charts.weeklyTrendChart?.setOption(option);
};

// 更新支付方式分布
const updatePaymentMethodChart = (billDetails) => {
  const paymentStats = {};
  let totalAmount = 0;

  billDetails.forEach(item => {
    if (item.收支 === '支出') {
      const method = item.支付方式 || '其他';
      const amount = Number(item['金额(元)']);
      paymentStats[method] = (paymentStats[method] || 0) + amount;
      totalAmount += amount;
    }
  });

  const data = Object.entries(paymentStats)
    .map(([name, value]) => ({
      name,
      value: Number(value.toFixed(2))
    }))
    .sort((a, b) => b.value - a.value);

  const option = {
    title: {
      text: '支付方式分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: (params) => {
        const percentage = ((params.value / totalAmount) * 100).toFixed(2);
        return `${params.name}<br/>金额: ¥${params.value}<br/>占比: ${percentage}%`;
      }
    },
    legend: {
      type: 'scroll',
      orient: 'vertical',
      right: 10,
      top: 20,
      bottom: 20
    },
    series: [{
      name: '支付方式',
      type: 'pie',
      radius: '50%',
      center: ['40%', '50%'],
      data: data,
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      },
      label: {
        show: true,
        formatter: '{b}\n¥{c}'
      }
    }]
  };

  charts.paymentMethodChart?.setOption(option);
};

// 更新消费时段分布
const updateTimeDistChart = (billDetails) => {
  const timeStats = new Array(24).fill(0);
  
  billDetails.forEach(item => {
    if (item.收支 === '支出') {
      const hour = new Date(item.交易时间).getHours();
      timeStats[hour] += Number(item['金额(元)']);
    }
  });

  const option = {
    title: {
      text: '消费时段分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: '{b}:00 - {b}:59<br/>消费金额: ¥{c}'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: Array.from({length: 24}, (_, i) => i),
      name: '时段',
      axisLabel: {
        formatter: '{value}:00'
      }
    },
    yAxis: {
      type: 'value',
      name: '金额 (元)'
    },
    series: [{
      data: timeStats.map(value => Number(value.toFixed(2))),
      type: 'bar',
      barWidth: '60%',
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#83bff6' },
          { offset: 1, color: '#188df0' }
        ])
      }
    }]
  };

  charts.timeDistChart?.setOption(option);
};

// 辅助函数：获取周数
const getWeekNumber = (date) => {
  const firstDayOfYear = new Date(date.getFullYear(), 0, 1);
  const pastDaysOfYear = (date - firstDayOfYear) / 86400000;
  return Math.ceil((pastDaysOfYear + firstDayOfYear.getDay() + 1) / 7);
};

// 更新消费类型分布图
const updateTypeChart = (billDetails) => {
  const typeStats = {};
  billDetails.forEach(item => {
    if (item.收支 === '支出') {
      const type = item.交易类型 || '其他';
      typeStats[type] = (typeStats[type] || 0) + Number(item['金额(元)']);
    }
  });

  const data = Object.entries(typeStats)
    .map(([name, value]) => ({
      name,
      value: Number(value.toFixed(2))
    }))
    .sort((a, b) => b.value - a.value);

  const option = {
    title: {
      text: '消费类型分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: ¥{c} ({d}%)'
    },
    legend: {
      type: 'scroll',
      orient: 'vertical',
      right: 10,
      top: 20,
      bottom: 20,
    },
    series: [{
      name: '消费类型',
      type: 'pie',
      radius: ['40%', '70%'],
      center: ['40%', '50%'],
      avoidLabelOverlap: true,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: true,
        formatter: '{b}\n¥{c}'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '14',
          fontWeight: 'bold'
        }
      },
      data: data
    }]
  };

  charts.typeChart?.setOption(option);
};

// 更新商户TOP10
const updateMerchantChart = (billDetails) => {
  const merchantStats = {};
  
  billDetails.forEach(item => {
    if (item.收支 === '支出') {
      const merchant = item.交易对方 || '其他';
      merchantStats[merchant] = (merchantStats[merchant] || 0) + Number(item['金额(元)']);
    }
  });

  const data = Object.entries(merchantStats)
    .map(([name, value]) => ({
      name: name.length > 12 ? name.substring(0, 12) + '...' : name,
      value: Number(value.toFixed(2)),
      fullName: name // 保存完整名称用于tooltip
    }))
    .sort((a, b) => b.value - a.value)
    .slice(0, 10);

  const option = {
    title: {
      text: '消费商户TOP10',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        const data = params[0];
        return `${data.data.fullName}<br/>消费金额: ¥${data.value}`;
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: '金额 (元)'
    },
    yAxis: {
      type: 'category',
      data: data.map(item => item.name),
      axisLabel: {
        interval: 0
      }
    },
    series: [{
      name: '消费金额',
      type: 'bar',
      data: data,
      itemStyle: {
        color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
          { offset: 0, color: '#ffd85c' },
          { offset: 1, color: '#ff9f7f' }
        ])
      }
    }]
  };

  charts.merchantChart?.setOption(option);
};

// 发送请求
const sendRequest = async () => {
  if (!inputString.value.trim()) {
    alert("输入不能为空！");
    return;
  }

  try {
    const res = await fetch("http://localhost:8070/getFicoData", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ input_string: inputString.value }),
    });

    if (!res.ok) {
      throw new Error(`HTTP error! status: ${res.status}`);
    }

    const data = await res.json();
    if (!data?.received_data?.bill_details) {
      throw new Error('Invalid data format');
    }

    response.value = data;
    updateCharts(data);
  } catch (error) {
    console.error("请求失败:", error);
    response.value = { error: "请求失败，请检查控制台日志" };
  }
};

// 监听窗口大小变化
const handleResize = () => {
  Object.values(charts).forEach(chart => {
    if (chart) {
      chart.resize();
    }
  });
};

onMounted(() => {
  initCharts();
  window.addEventListener('resize', handleResize);
  // 初始化时强制执行一次resize
  nextTick(() => {
    handleResize();
  });
});

onUnmounted(() => {
  Object.values(charts).forEach(chart => {
    chart?.dispose();
  });
  window.removeEventListener('resize', handleResize);
});
</script>

<style scoped>
.page-container {
  height: 100vh;
  overflow-y: auto;
  padding: 20px;
  box-sizing: border-box;
}

.dashboard-container {
  max-width: 1920px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f5f7fa;
}

.input-container {
  text-align: center;
  margin-bottom: 20px;
}

input {
  width: 300px;
  padding: 10px 15px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin-right: 10px;
  font-size: 14px;
  transition: all 0.3s;
}

input:focus {
  border-color: #409eff;
  outline: none;
}

button {
  padding: 10px 20px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

button:hover {
  background-color: #66b1ff;
}

.stat-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.stat-title {
  color: #909399;
  font-size: 14px;
  margin-bottom: 10px;
}

.stat-value {
  color: #303133;
  font-size: 24px;
  font-weight: bold;
}

.stat-value.income {
  color: #67c23a;
}

.stat-value.expense {
  color: #ff6b6b;
}

.stat-trend {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.chart-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.chart-container {
  min-height: 400px;
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.chart {
  width: 100%;
  height: 100%;
  min-height: 360px;
}

@media screen and (max-width: 1200px) {
  .chart-grid {
    grid-template-columns: 1fr;
  }
  
  .chart-container {
    min-height: 350px;
  }
}
</style>